var path = require("path");
var dao = require(path.join(process.cwd(), "dao/DAO"));
var formatData = require("./formatData.js");

function doCreateAddress(params) {
    return new Promise(function (resolve, reject) {
        dao.create("AddressModel", params, function (err, address) {
            if (err) return reject({
                msg: "添加地址：添加失败！",
                code: err.name == "SequelizeValidationError" ? 400 : 500,
                stack: err
            });
            resolve({
                msg: "添加地址：添加成功！",
                code: 201,
                data: formatData(address)
            });
        });
    });
}

function doUpdateAddress(id, data) {
    return new Promise(function (resolve, reject) {
        if (!id || isNaN(parseInt(id))) return reject({
            msg: "更新地址：ID不合法！",
            code: 400,
            stack: null
        });
        dao.update("AddressModel", id, data, function (err, address) {
            if (err) return reject({
                msg: "更新地址：更新失败！",
                code: err.name == "SequelizeValidationError" ? 400 : 500,
                stack: err
            });
            resolve({
                msg: "更新地址：更新成功！",
                code: 200,
                data: formatData(address)
            });
        });
    });
}

/**
 *  添加地址
 * 
 *  @param {[type]}   params 地址数据 
 *  @param {Function} cb  回调函数
 */
module.exports.createAddress = function (params, cb) {
    // 如果is_default为true,则去数据库查找有没有已经设为默认的地址
    if (params.is_default) {
        dao.findOne("AddressModel", {
            is_default: 1,
            user_id: params.user_id
        }, function (err, address) {
            if (err) return cb({
                msg: "添加地址：查询失败！",
                code: err.name == "SequelizeValidationError" ? 400 : 500,
                stack: err
            });
            var batchFns = [doCreateAddress(params)];
            // 如果存在已经设为默认的地址,则把该默认地址去掉
            if (address) {
                batchFns.push(doUpdateAddress(address.id, { is_default: false }));
            }
            Promise.all(batchFns).then(res => cb(null, res[0])).catch(cb);
        });
        // 否则直接创建
    } else {
        doCreateAddress(params).then(res => cb(null, res)).catch(cb);
    }
}

/**
 *  删除地址
 * 
 *  @param  {[type]}   id     地址ID
 *  @param  {Function} cb     回调函数
 */
module.exports.deleteAddress = function (id, cb) {
    if (!id) return cb({
        msg: "删除地址：ID不能为空！",
        code: 400,
        stack: null
    });
    if (!Array.isArray(id)) id = [id];
    if (id.every(item => isNaN(parseInt(item)))) return cb({
        msg: "删除地址：ID必须是数字！",
        code: 400,
        stack: null
    });
    dao.destroyMany("AddressModel", id, function (err) {
        if (err) return cb({
            msg: "删除地址：删除失败！",
            code: 500,
            stack: err
        });
        cb(null, {
            msg: "删除地址：删除成功！",
            code: 200,
            data: null
        });
    });
}

/**
 *  更新地址
 * 
 *  @param  {[type]}   id   地址ID
 *  @param  {[type]}   data 新数据
 *  @param  {Function} cb   回调函数
 */
module.exports.updateAddress = function (id, data, cb) {
    // 如果is_default为true,则去数据库查找有没有已经设为默认的地址
    if (data.is_default) {
        dao.findOne("AddressModel", {
            is_default: 1,
            user_id: data.user_id
        }, function (err, address) {
            if (err) return cb({
                msg: "更新地址：查询失败！",
                code: err.name == "SequelizeValidationError" ? 400 : 500,
                stack: err
            });
            var batchFns = [doUpdateAddress(id, data)];
            // 如果存在已经设为默认的地址,则把该默认地址去掉
            if (address && address.id!=id) {
                batchFns.push(doUpdateAddress(address.id, { is_default: false }));
            }
            Promise.all(batchFns).then(res => cb(null, res[0])).catch(cb);
        });
        // 否则直接创建
    } else {
        doUpdateAddress(id, data).then(res => cb(null, res)).catch(cb);;
    }
}

/**
 *  根据条件获取地址列表
 *  @param  {[type]}   conditions 查询条件
 *  conditions{
        "where" : 条件查询,
        "order" : 排序
        "pagenum" : 页数,
        "pagesize" : 每页长度
    }
 *  @param  {Function} cb         回调函数
 */
module.exports.getAllAddresss = function (conditions, cb) {
    if (!conditions.pagenum || conditions.pagenum <= 0) return cb({
        msg: "获取地址列表：pagenum 参数不合法！",
        code: 400,
        stack: null
    });
    if (!conditions.pagesize || conditions.pagesize <= 0) return cb({
        msg: "获取地址列表：pagesize 参数不合法！",
        code: 400,
        stack: null
    });
    dao.countByConditions("AddressModel", conditions, function (err, count) {
        if (err) return cb({
            msg: "获取地址列表：获取总数失败！",
            code: 500,
            stack: err
        });
        pagenum = parseInt(conditions["pagenum"]);
        pagesize = parseInt(conditions["pagesize"]);
        pageCount = Math.ceil(count / pagesize);
        offset = (pagenum - 1) * pagesize;
        if (offset >= count) {
            offset = count;
        }
        limit = pagesize;
        conditions["offset"] = offset;
        conditions["limit"] = limit;
        conditions["order"] = "-id";
        dao.list("AddressModel", conditions, function (err, address) {
            if (err) return cb({
                msg: "获取地址列表：获取分页数据失败！",
                code: 500,
                stack: err
            });
            var resultDta = {};
            resultDta["total"] = count;
            resultDta["pagenum"] = pagenum;
            resultDta["address"] = address.map(formatData);
            cb(null, {
                msg: "获取地址列表：获取分页数据成功！",
                code: 200,
                data: resultDta
            });
        });
    });
}

/**
 *  根据id获取地址对象
 * 
 *  @param  {[type]}   id 地址ID
 *  @param  {Function} cb 回调函数
 */
module.exports.getAddressById = function (id, cb) {
    if (!id || isNaN(parseInt(id))) return cb({
        msg: "获取地址对象：ID不合法！",
        code: 400,
        stack: null
    });
    dao.findByID("AddressModel", id, function (err, address) {
        if (err) return cb({
            msg: "获取地址对象：获取失败！",
            code: 500,
            stack: err
        });
        if (!address) return cb({
            msg: "获取地址对象：对象不存在！",
            code: 403,
            stack: null
        });
        cb(null, {
            msg: "获取地址对象：获取成功！",
            code: 200,
            data: formatData(address)
        });
    });
}

/**
 *  获取默认地址
 *  @param  {[type]}   conditions 查询条件
 *  conditions{
        "where" : 条件查询,
    }
 *  @param  {Function} cb         回调函数
 */
module.exports.getDefaultAddress = function (conditions, cb) {
    dao.findOne("AddressModel", conditions, function (err, address) {
        if (err) return cb({
            msg: "获取地址数据失败！",
            code: 500,
            stack: err
        });
        cb(null, {
            msg: "获取地址数据成功！",
            code: 200,
            data: formatData(address)
        });
    });
}